package com.sunnay.service.impl;

import cn.hutool.json.JSONUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gaby.commons.exception.BssException;
import com.sunnay.constant.SendConstant;
import com.sunnay.entity.AppShopLiveInfoEntity;
import com.sunnay.entity.UserBidEntity;
import com.sunnay.enums.GbCodeEnum;
import com.sunnay.exception.DataException;
import com.sunnay.mapper.AppShopLiveInfoMapper;
import com.sunnay.service.AppShopLiveInfoService;
import com.sunnay.service.UserBidService;
import com.sunnay.util.CommUtils;
import com.sunnay.util.OkHttpClientUtils;
import com.sunnay.vo.auth.SystemUser;
import com.sunnay.vo.live.BidResponseVo;
import com.sunnay.vo.live.LayerVo;
import com.sunnay.vo.live.OfferVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.net.Authenticator;
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication;
import java.net.Proxy;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
@Slf4j
public class AppShopLiveInfoServiceImpl extends ServiceImpl<AppShopLiveInfoMapper, AppShopLiveInfoEntity> implements AppShopLiveInfoService {

    @Resource
    private UserBidService userBidService;

    @Autowired
    private OkHttpClientUtils okHttpClientUtils;


    @Override
    public List<AppShopLiveInfoEntity> liveShopList(SystemUser systemUser) {
        return this.list(Wrappers.<AppShopLiveInfoEntity>query().lambda().eq(AppShopLiveInfoEntity::getWxId, systemUser.getWxId()));
    }

    @Override
    public List<UserBidEntity> liveShopSmallList(SystemUser systemUser) {
        return userBidService.smallList();
    }

    @Override
    public Object liveShopOffer(OfferVo offerVo, SystemUser systemUser) throws IOException {
        UserBidEntity userBidEntity = isExistSmallInfo(offerVo.getSmallId());
        Map<String,String> header = new HashMap<String,String>();
        header.put("Cookie","ut="+userBidEntity.getUt());
        //OkHttpUtils okHttpUtils = new OkHttpUtils();
        log.info("请求参数：{}","roomId="+offerVo.getRoomId()+"&userinfoUri="+offerVo.getShopUri());
        //String result =  okHttpUtils.post(CommUtils.LiveUtils.SEND_SALE_LAYER,"roomId="+offerVo.getRoomId()+"&userinfoUri="+offerVo.getShopUri(),OkHttpClientUtils.FORM_DATA,header);
        String result = okHttpClientUtils.doPostJson(CommUtils.LiveUtils.SEND_SALE_LAYER,"roomId="+offerVo.getRoomId()+"&userinfoUri="+offerVo.getShopUri(),header,OkHttpClientUtils.FORM_DATA);
        log.info("result={}",result);
        if(StringUtils.isBlank(result))
            throw new BssException("出价失败");
        JSONObject jsonObject = JSONUtil.parseObj(result);
        LayerVo layerVo = JSONUtil.toBean(jsonObject.getStr("data"),LayerVo.class);
        log.info("直播间拍品信息：{}",JSONUtil.toJsonStr(layerVo));
        if(StringUtils.isBlank(layerVo.getUri()))
            throw new DataException(GbCodeEnum.USER_LIVE_PRODUCT_NOT_FOUND.getKey(),GbCodeEnum.USER_LIVE_PRODUCT_NOT_FOUND.getValue());
        if ((layerVo.getEndTime() - layerVo.getOpenTime()) < 0)
            throw new DataException(GbCodeEnum.USER_DEPOSIT_END_TIME.getKey(),GbCodeEnum.USER_DEPOSIT_END_TIME.getValue());
        int totalBidMoney = 0;
        if(layerVo.getBidmoney() > 0 && layerVo.getNowPrice() == 0)
            totalBidMoney = layerVo.getBidmoney();
        else
            totalBidMoney = layerVo.getNowPrice() + layerVo.getIncrease();

        String[] headers = {"Cookie","ut="+userBidEntity.getUt(),"User-Agent",CommUtils.USER_AGENT};
        okHttpClientUtils.doGet(CommUtils.LiveUtils.SALE_DETAIL_PARK+layerVo.getUri(),headers);
        String url = String.format(CommUtils.LiveUtils.USER_LIVE_BID,totalBidMoney,layerVo.getUri(),offerVo.getRoomId(),userBidEntity.getUserInfoUri());
        result = okHttpClientUtils.doGet(url,headers);
        BidResponseVo bidVo = JSONUtil.toBean(result, BidResponseVo.class);
        UserBidEntity update = new UserBidEntity();
        update.setId(offerVo.getSmallId());
        if(StringUtils.contains(bidVo.getMsg(),"success")) {
            //出价成功，记录日志，扣除积分
            return "出价成功，出价金额【"+totalBidMoney+"】";
        }
        else if(StringUtils.contains(bidVo.getMsg(),"您出价太快了")){
            return "您出价太快了";
        }
        else if(StringUtils.contains(bidVo.getMsg(),"保证金")){
            update.setStatus("2");
        }
        else if(StringUtils.contains(bidVo.getMsg(),"由于您的异常行为") ){
            update.setStatus("2");
        }
        else if(StringUtils.contains(bidVo.getMsg(),"未登录")){
            update.setStatus("2");
        }
        else if(StringUtils.contains(bidVo.getMsg(),"超过限制")){
            update.setStatus("3");
        }
        else if(StringUtils.contains(bidVo.getMsg(),"违约次数")){
            update.setStatus("5");
        }
        userBidService.updateById(update);
        return bidVo.getMsg();
    }

    @Override
    public void liveShopAttention(OfferVo offerVo, SystemUser systemUser) {
        UserBidEntity userBidEntity = isExistSmallInfo(offerVo.getSmallId());
        Map<String,String> header = new HashMap<String,String>();
        header.put("Cookie","ut="+userBidEntity.getUt());
        String result = okHttpClientUtils.doPostJson(CommUtils.LiveUtils.ATTENTION_LIVE, "type=1&ajax=1&userinfoUri=" + userBidEntity.getUserInfoUri() + "&roomId=" + offerVo.getRoomId(), header,OkHttpClientUtils.FORM_DATA);
        if (StringUtils.isBlank(result))
            throw new BssException("关注失败");
        com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(result);
        String code = jsonObject.getString("code");
        if (StringUtils.equals(code, "900") || StringUtils.equals(code, "100") || StringUtils.equals(code,"1004014")) {
            UserBidEntity update = new UserBidEntity();
            update.setId(offerVo.getSmallId());
            update.setStatus("4");
            userBidService.updateById(update);
            throw new DataException("小号已掉线或已被平台拉黑，请选择其他小号");
        }
    }

    @Override
    public void sendMsgInfo(OfferVo offerVo, SystemUser systemUser) {
        UserBidEntity userBidEntity = isExistSmallInfo(offerVo.getSmallId());
        SendConstant sendConstant = new SendConstant(userBidEntity);
        sendConstant.userSign(offerVo.getShopUri());
        sendConstant.userLogin(userBidEntity.getUserInfoUri());
        sendConstant.applyGroup(offerVo.getTimId());
        sendConstant.getMsg();
        String result = sendConstant.startSendMessage(offerVo.getContent(), offerVo.getTimId(), userBidEntity.getUserInfoUri(), userBidEntity.getGrade());
        if(!StringUtils.equals(result,"success"))
            throw new DataException("消息发送失败");
    }

    @Override
    public void shareRoom(OfferVo offerVo, SystemUser systemUser) {
        UserBidEntity userBidEntity = isExistSmallInfo(offerVo.getSmallId());
        Map<String,String> header = new HashMap<>();
        header.put("Cookie","ut="+userBidEntity.getUt());
        okHttpClientUtils.doPostJson(CommUtils.LiveUtils.SHARE_LIVE_TIP+ userBidEntity.getUserInfoUri(),"roomId="+offerVo.getRoomId(),header,OkHttpClientUtils.FORM_DATA);
        String result = okHttpClientUtils.doGet(CommUtils.LiveUtils.SHARE_LIVE_L+offerVo.getShopUri(),header);
        if(StringUtils.isEmpty(result))
            throw new DataException("分享失败");
        JSONObject jsonObject = JSONUtil.parseObj(result);
        String code = jsonObject.getStr("code");
        if (StringUtils.equals(code, "900") || StringUtils.equals(code,"1004014")) {
            UserBidEntity update = new UserBidEntity();
            update.setId(offerVo.getSmallId());
            update.setStatus("4");
            userBidService.updateById(update);
            throw new DataException("小号已掉线或已被平台拉黑，请选择其他小号");
        }
    }

    private UserBidEntity isExistSmallInfo(Integer id){
        UserBidEntity userBidEntity = userBidService.getById(id);
        Optional.ofNullable(userBidEntity).orElseThrow(()->new DataException(GbCodeEnum.USER_LIVE_SMALL_NOT_FOUND.getKey(),GbCodeEnum.USER_LIVE_SMALL_NOT_FOUND.getValue()));
        return userBidEntity;
    }


    private Proxy getProxy(){
        System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
        Authenticator.setDefault(new Authenticator() {
                 public PasswordAuthentication getPasswordAuthentication() {
                     //serverProxyUsername 用户名
                     //serverProxyPassword 密码
                     return new PasswordAuthentication(CommUtils.proxyUser, CommUtils.proxyPass.toCharArray());
                 }
             }
        );
        Proxy proxy = new Proxy(Proxy.Type.HTTP,new InetSocketAddress(CommUtils.proxyServer,CommUtils.proxyPort));
        return proxy;
    }
}
